package com.cool.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.cool.cloud.entity.AlipayBean;
import com.cool.cloud.service.impl.FileStoreServiceImpl;
import com.cool.cloud.service.impl.PayServiceImpl;
import com.cool.cloud.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.UUID;

@Controller
public class AlipayController extends BaseController {
    @Autowired
    PayServiceImpl PayService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    FileStoreServiceImpl fileStoreService;

    @RequestMapping("pay")
    @ResponseBody
    public String alipay(String money) throws AlipayApiException {
        //订单号
        String id = UUID.randomUUID().toString();
        String subject = "CoolCloud钱包充值订单";
        String total_amount = money;
        String body = "用于充值钱包";
        AlipayBean al = new AlipayBean();
        al.setOut_trade_no(id);
        al.setSubject(subject);
        al.setTotal_amount(new StringBuffer().append(total_amount));
        al.setBody(body);
        session.setAttribute("paymoney", money);
        return PayService.alipy(al);
    }

    @RequestMapping("successpay")
    public String successPay() throws AlipayApiException {
        Integer paymoney = Integer.valueOf((String) session.getAttribute("paymoney"));
        loginUser.setWallet(loginUser.getWallet() + paymoney);
        userService.update(loginUser);
        session.removeAttribute("paymoney");
        return "main/wallet";
    }

    @RequestMapping("payRom")
    @ResponseBody
    public String payRom(String payRom) throws AlipayApiException {
        Integer IntpayRom = Integer.valueOf(payRom);
        HashMap<String, String> rs = new HashMap();
        //rom多少钱，减少钱
        Integer money = IntpayRom / 100;
        if (loginUser.getWallet() - money < 0) {
            return "fail-余额不足,仅剩" + loginUser.getWallet();
        }
        loginUser.setWallet(loginUser.getWallet() - money);
        userService.update(loginUser);
        //rom多少mb,加mb
        fileStoreService.editMaxSize(loginUser.getFileStoreId(), fileStoreService.getMaxSize(loginUser.getFileStoreId()) + IntpayRom * 1024);
        return "success-充值成功";
    }
}
